﻿#include "ssTimer.h"

namespace StarSeeker
{
///////////////////////////////////时差计时器//////////////////////////////////
ssDiffTimer::ssDiffTimer()
{
	m_curTime.u64p = 0;
	m_lastTime.u64p = 0;
	m_difference.u64p = 0;
	m_type = 0;
	m_totla.u64p = 0;
}

void ssDiffTimer::Init(u8 type)
{
	m_type = type;
	if(m_type==SS_DIFF_TIMER_TYPE_SEC)
	{
		m_curTime = m_lastTime = ssTime::GetTimeNow();
	}
	else if(m_type==SS_DIFF_TIMER_TYPE_MS)
	{
		m_curTime = m_lastTime = ssTime::GetTimeNowMS();
	}
	else if(m_type==SS_DIFF_TIMER_TYPE_CLOCK)
	{
		m_curTime.u64p = m_lastTime.u64p = ::clock();
	}
	m_totla.u64p = 0;
}

void ssDiffTimer::UpdateTime()
{
	if(m_type==SS_DIFF_TIMER_TYPE_SEC)
	{
		m_curTime = ssTime::GetTimeNow();
	}
	else if(m_type==SS_DIFF_TIMER_TYPE_MS)
	{
		m_curTime = ssTime::GetTimeNowMS();
	}
	else if(m_type==SS_DIFF_TIMER_TYPE_CLOCK)
	{
		m_curTime.u64p = ::clock();
	}
	m_difference.u64p = m_curTime.u64p - m_lastTime.u64p;
	m_lastTime = m_curTime;
#ifndef _WIN32
	if (m_type == SS_DIFF_TIMER_TYPE_CLOCK)
	{
		m_difference.u64p /= 1000;
		m_difference.u64p += m_sleepMs;
	}
#endif // !_WIN32
	m_totla.u64p += m_difference.u64p;
}

void ssDiffTimer::ResetTotal()
{
	m_totla.u64p = 0;
}

bool ssDiffTimer::IsAccumulatedTimeUp(u32 interval)
{
	UpdateTime();
	if (m_totla.u32p > interval)
	{
		m_totla.u64p = 0;
		return true;
	}
	return false;
}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////帧速计时器///////////////////////////////////
ssFrameTimer::ssFrameTimer()
	:m_isBuiltIn(false), m_frameCount(0),m_tickCount(0),m_interval(30000)
{
	m_mspf.i64p = 0;
	m_fps.i64p = 0;
}

void ssFrameTimer::Init(u32 interval, bool isBuiltIn)
{
	m_isBuiltIn = isBuiltIn;
	if (isBuiltIn)
	{
		m_timer.Init(SS_DIFF_TIMER_TYPE_MS);
	}
	m_interval = interval;
}

bool ssFrameTimer::UpdateAndCompute(u32 ms)
{
	Update(ms);
	if (m_tickCount > m_interval)
	{
		Compute();
		return true;
	}
	return false;
}

void ssFrameTimer::Update(u32 ms)
{
	if (m_isBuiltIn)
	{
		m_timer.UpdateTime();
		m_tickCount += m_timer.GetDifference().u64p;
	}
	else
	{
		m_tickCount += ms;
	}
	++m_frameCount;
}

void ssFrameTimer::Compute()
{
	if (m_frameCount > 0)
	{
		m_mspf.u64p = m_tickCount / m_frameCount;
		m_fps.u64p = m_frameCount*1000 / m_tickCount;
		m_tickCount = 0;
		m_frameCount = 0;
	}
}

//////////////////////////////////////////////////////////////////////////////
}
